package com.softer.chengxin.userinfo.dao.provider;

import com.softer.chengxin.common.domin.Page;
import com.softer.chengxin.userinfo.entity.UserSearch;

import java.util.Map;

/**
 * @author Gong Zhiyang
 * @date 2018/10/18
 */
public class UserInfoDaoProvider {
    /**
     * 加载用户列表
     *
     * @param map
     * @return
     */
    public String load(Map<String, Object> map) {
        StringBuffer sql = new StringBuffer(20);
        Page page = (Page) map.get("page");
        sql.append("SELECT a.id,a.login_name AS username,a.`name`,a.area as corpid,d.name AS areaName,c.`name` as adder,");
        sql.append(" DATE_FORMAT(a.gmt_create, '%Y-%m-%d') AS adderTime,b.roles_name as roleName,a.role_id as rolesid");
        sql.append(" FROM `manager_user` a LEFT JOIN roules b ON a.role_id=b.id ");
        sql.append(" LEFT JOIN manager_user c ON c.login_name=a.adder ");
        sql.append(" LEFT JOIN district_street d ON d.id = SUBSTRING_INDEX(a.area,',',1)  ");
        sql.append(" WHERE a.adder =#{loginName}");
        commonSql(sql,map);
        sql.append(" LIMIT ");
        sql.append(page.getBeginIndex()).append(",").append(page.getLimit());
        return sql.toString();
    }

    public String getUserNum(Map<String, Object> map) {
        StringBuffer sql = new StringBuffer(20);
        sql.append("SELECT COUNT(*) FROM `manager_user` a LEFT JOIN roules b ON a.role_id=b.id ");
        sql.append(" where a.adder=#{loginName}");
        commonSql(sql,map);
        return sql.toString();
    }

    private void commonSql(StringBuffer sql, Map<String, Object> map) {
        UserSearch userSearch = (UserSearch) map.get("userSearch");
        if (userSearch.getRoleId() != null) {
            sql.append(" and a.role_id=#{userSearch.roleId}");
        }
        if (userSearch.getDistrict() != null) {
            sql.append(" and FIND_IN_SET(#{userSearch.district},a.area)");
        }
        if (userSearch.getStreet() != null) {
            sql.append(" and FIND_IN_SET(#{userSearch.street},a.area)");
        }
        if (userSearch.getCommunity() != null) {
            sql.append(" and FIND_IN_SET(#{userSearch.community},a.area)");
        }
    }
}
